package com.emep.changzhi.analyse.service.Technology;

import com.emep.changzhi.analyse.entity.Technology.SNCRDenitrification;
import com.emep.changzhi.analyse.entity.information.SysmessageTemplateInfo;
import com.emep.changzhi.analyse.repository.Technology.SNCRDenitrificationRepository;
import com.emep.changzhi.analyse.utils.MapUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;

/**
 * @author xy
 * @Description: SNCR脱销
 * @date 2018/6/26 17:35
 * @version V1.0
 */
@Slf4j
@Service
public class SNCRDenitrificationService {
    @Resource
    private SNCRDenitrificationRepository sncrDenitrificationRepository;

    /**
     * 添加
     * @param payload
     * @return
     */
    public SNCRDenitrification add(Map<String, Object> payload){
        SNCRDenitrification sncrDenitrification = null;
        try {
            SNCRDenitrification sncrDenitrification1 = (SNCRDenitrification) MapUtils.convertMap(SNCRDenitrification.class,payload);
            sncrDenitrification = sncrDenitrificationRepository.save(sncrDenitrification1);
        }catch (Exception e){
            log.error(e.getClass().getName()+":"+ e.getMessage());
            log.error(e.getLocalizedMessage());
        }
        return sncrDenitrification;
    }
    /**
     * 查询
     */
    public Page<SNCRDenitrification> list(Integer page, Integer rows, Map<String,Object> payload){
        //规格定义
        Pageable pageable = new PageRequest(page-1,rows , Sort.Direction.ASC, "saveDate"); //页码：前端从1开始，jpa从0开始，做个转换
        Page<SNCRDenitrification> studentPage = sncrDenitrificationRepository.findAll(new Specification<SNCRDenitrification>(){
            @Override
            public Predicate toPredicate(Root<SNCRDenitrification> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                if(!payload.isEmpty()){
                    if(payload.get("begin") != null && payload.get("end") != null){
                        Predicate p1 = criteriaBuilder.between(root.get("saveDate").as(String.class),payload.get("begin").toString(),payload.get("end").toString());
                        query.where(criteriaBuilder.or(p1));

                    }
                }
                return query.getRestriction();
            }
        },pageable);
        return studentPage;
    }
}
